---
category: Date Time
contributors:
    - kwaimind
created: '2020-07-27'
title: Calculate the number of months between two dates
updated: '2021-10-13'
---

**JavaScript version**

```js monthDiff.js
const monthDiff = (startDate, endDate) =>
    Math.max(0, (endDate.getFullYear() - startDate.getFullYear()) * 12 - startDate.getMonth() + endDate.getMonth());
```

**TypeScript version**

```ts monthDiff.ts
const monthDiff = (startDate: Date, endDate: Date): number =>
    Math.max(0, (endDate.getFullYear() - startDate.getFullYear()) * 12 - startDate.getMonth() + endDate.getMonth());
```

**Example**

```js example.js
monthDiff(new Date('2020-01-01'), new Date('2021-01-01')); // 12
```
